﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace Jinndev.Json {

    public class JsonSetting {

        private JObject obj;

        public JsonSetting() {
            obj = new JObject();
        }

        public JsonSetting(string json) {
            obj = JObject.Parse(json);
        }

        public void Set<T>(string key, T value) {
            if (value is JToken) {
                obj[key] = value as JToken;
            }
            else {
                obj[key] = new JValue(value);
            }
        }

        public T Get<T>(string key, T defaultValue = default) {
            JToken token = obj.ContainsKey(key) ? obj[key] : null;
            if (typeof(T).IsEnum) {
                return token == null ? defaultValue : (T)Enum.ToObject(typeof(T), token.Value<int>());
            }
            return token == null ? defaultValue : token.Value<T>();
        }

        public string ToString(Formatting formatting, params JsonConverter[] converters) {
            return obj == null ? "{}" : obj.ToString(formatting, converters);
        }

        public override string ToString() {
            return obj == null ? "{}" : obj.ToString();
        }

        public string ToString(bool prettyPrint) {
            return obj == null ? "{}" : obj.ToString(prettyPrint ? Formatting.Indented : Formatting.None);
        }

    }

}